package com.mihu.stmall.manager.controller.api;

import com.github.pagehelper.PageInfo;
import com.mihu.stmall.manager.entiy.Category;
import com.mihu.stmall.manager.entiy.Result;
import com.mihu.stmall.manager.service.CategoryService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


@RestController
//相当于controller和ResponseBody的结合体
//1 将当前类放到Spring的bean容器
//2 所有处理方法 返回JSON格式的数据
@RequestMapping("/api/category")
//给当前类
public class APICategoryController {

    //自动注入service层对象
    @Resource
    private CategoryService categoryService;
    //添加 需要post请求
    @PostMapping
    public Result add(@RequestBody Category category){
        try {
            int code = categoryService.add(category);
            //添加成功
            return Result.success();

        } catch (Exception e) {
            e.printStackTrace();
            //添加失败
            return Result.error(e.getMessage());
        }
    }
    //删除
@DeleteMapping
   public Result remove(Integer id){
       try {
           int code = categoryService.remove(id);
           //成功
           return Result.success();
       } catch (Exception e) {
           e.printStackTrace();
           //失败
           return Result.error(e.getMessage());
       }
   }
    //修改
    @PutMapping
    public Result edit(@RequestBody Category category)  {
        try {
            int code = categoryService.edit(category);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    @GetMapping
    public Result get( Integer page,Integer limit,Category category){
        if (page == null){
            List<Category> list = categoryService.search(category);

            return Result.success(list);
        }else {
           PageInfo pageInfo = categoryService.searchByPage(page,limit,category);
           return Result.success(pageInfo);
        }
    }
    //根据ID进行查询
    //通过路径参数传递id
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") Integer id){
        //PathVariable取出路径中参数 绑定到id上
        Category category = categoryService.getById(id);
        if (category==null){
            return Result.error("id不存在");

        }else {
            return Result.success(category);
        }
    }

}

